﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Data;
using System.IO;

namespace Agro.Library {
    public class ExcelResult : ActionResult {
        DataTable _dataTable;
        string _fileName;
        int[] _columnWiths = null;
        public ExcelResult(DataTable dataTable) {
            _dataTable = dataTable;
            this._fileName = DateTime.Now.ToFileTime().ToString();
        }
        public ExcelResult(DataTable dataTable, string fileName) {
            _dataTable = dataTable;
            _fileName = fileName;
        }

        public ExcelResult(DataTable dataTable, string fileName, int[] columnWiths) {
            _dataTable = dataTable;
            _fileName = fileName;
            _columnWiths = columnWiths;
        }

        public override void ExecuteResult(ControllerContext context) {
            context.HttpContext.Response.ContentType = "application/vnd.ms-excel";
            context.HttpContext.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", _fileName));
            context.HttpContext.Response.Clear();
            using (MemoryStream file = new MemoryStream()) {
                NPOIHelper.WriteExcelToStream(_dataTable, file, _columnWiths);
                file.WriteTo(context.HttpContext.Response.OutputStream);
            }
            context.HttpContext.Response.End();
        }
    }
}
